package cashpointer.mobile;

import android.app.Activity;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Intent;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.CheckBox;
import android.widget.TextView;
import cashpointer.mobile.dao.DaoModel.Cashpoints;
import cashpointer.mobile.dao.DaoModel.Countries;
import cashpointer.mobile.dao.DaoModel.Owners;
import cashpointer.mobile.dao.DaoModel.Regions;
import cashpointer.mobile.support.PreferencesManager;

public class CashpointActivity extends Activity {
	
	/**
	 * Opcje menu.
	 */
	private static final int MENU_QUIT = Menu.FIRST;
	private static final int MENU_SHOW_MAP = Menu.FIRST + 1;
	private static final int MENU_SMS = Menu.FIRST + 2;
	
	/**
	 * Logi
	 */
	//private static String LOG_TAG = "CashpointActivity";
	
	/**
	 * Dane bankomatu
	 */
	private Uri uriOfSelectedCashpoint = null;
	private double latitude = 0.0;
	private double longitude = 0.0;
	private String cityStreet = null;
    private boolean marked = false;
    private String owner = null;
    private String info = null;
    private String time = null;
    private String regionCountry = null;

	/**
     * The columns we are interested in from the database
     */
	private static final String[] CASHPOINTS_PROJECTION = new String[] {
    	Cashpoints._ID, // 0
    	Cashpoints.ADDRESS_CITY, // 1
    	Cashpoints.ADDRESS_STREET, // 2
    	Cashpoints.MARKED, // 3
    	Cashpoints.ADDRESS_INFO, // 4
    	Cashpoints.ADDRESS_LATITUDE, // 5
    	Cashpoints.ADDRESS_LONGITUDE, // 6
    	Cashpoints.TIME, // 7
    	Cashpoints.OWNER_ID, // 8
    	Cashpoints.COUNTRY_ID, // 9
    };
	
	private static final String[] OWNERS_PROJECTION = new String[] {
    	Owners._ID, // 0
    	Owners.NAME, // 1
    };

	private static final String[] COUNTRIES_PROJECTION = new String[] {
    	Countries._ID, // 0
    	Countries.NAME, // 1
    	Countries.REGION_ID, // 2
    };
	
	private static final String[] REGIONS_PROJECTION = new String[] {
    	Regions._ID, // 0
    	Regions.NAME, // 1
    };
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setTheme(android.R.style.Theme_Light);
        setContentView(R.layout.cashpoint);
        
        // Pobieram identyfikator bankomatu wybranego z listy
        Intent intent = getIntent();
        long selectedId = intent.getLongExtra(PreferencesManager.CASHPOINT_SELECTED_ID, (long)-1);
        if (selectedId == (long)-1) {
        	selectedId = PreferencesManager.getLong(getApplicationContext(), PreferencesManager.CASHPOINT_SELECTED_ID, (long)-1);
        }
        if (selectedId == (long)-1) {
	    	//Log.w(LOG_TAG, "Nieporawne id: " + selectedId);
	    	quit();
        } else {
        	PreferencesManager.setPreference(getApplicationContext(), PreferencesManager.CASHPOINT_SELECTED_ID, selectedId);
        }
        
        // Przygotowanie danych bankomatu
        prepareData(selectedId);
     	
        // Ustawiam zawartosc pola "Wojewodztwo i powiat"
        TextView regionCountryTextView = (TextView)findViewById(R.id.cashpointRegionCountry);
        if (regionCountry != null) {
        	regionCountryTextView.setText(regionCountry);
        } else {
        	regionCountryTextView.setText("brak danych");
        }
        
        // Ustawiam zawartosc pola "Miasto"
        TextView cityStreetTextView = (TextView)findViewById(R.id.cashpointCityStreet);
        if (cityStreet != null) {
        	cityStreetTextView.setText(cityStreet);
        } else {
        	cityStreetTextView.setText("brak danych");
        }
        
        // Ustawiam zawartosc pola "Info"
        TextView infoTextView = (TextView)findViewById(R.id.cashpointInfo);
        if (info != null) {
        	infoTextView.setText(info);
        } else {
        	infoTextView.setText("brak danych");
        }
        
        // Ustawiam zawartosc pola "Godziny otwarcia"
        TextView timeTextView = (TextView)findViewById(R.id.cashpointTime);
        if (time != null) {
        	timeTextView.setText(time);
        } else {
        	timeTextView.setText("brak danych");
        }
        
        // Ustawiam zawartosc pola "Siec bankomatow"
        TextView ownerTextView = (TextView)findViewById(R.id.cashpointOwner);
        if (owner != null) {
        	ownerTextView.setText(owner);
        } else {
        	ownerTextView.setText("brak danych");
        }
        
        // Ustawiam zawartosc pola "Ulubione"
        CheckBox markedCheckBox = (CheckBox)findViewById(R.id.cashpointMarkedCheckBox);
        markedCheckBox.setChecked(marked);
        markedCheckBox.setOnClickListener(new OnClickListener() {
	        public void onClick(View v) {
	        	CashpointActivity.this.changeMarkedState();
	        }
        }); 
    }
    
    /**
     * Funkcja przygotowujaca dane bankomatu
     * @param selectedId
     */
	private void prepareData(long selectedId) {
		// Adres do wybranego rekordu z bazy (o danym id)
        uriOfSelectedCashpoint = ContentUris.withAppendedId(Cashpoints.CONTENT_URI, selectedId);
		
        // Tworze kursor
        Cursor cashpointCursor = managedQuery(uriOfSelectedCashpoint, CASHPOINTS_PROJECTION, null, null, Cashpoints.DEFAULT_SORT_ORDER);			

        // Przegladanie kursora
		if (cashpointCursor != null && cashpointCursor.moveToFirst()) {
	        int addressCityColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_CITY);
	        int addressStreetColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_STREET);
	        int markedColumn = cashpointCursor.getColumnIndex(Cashpoints.MARKED);
	        int infoColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_INFO);
	        int timeColumn = cashpointCursor.getColumnIndex(Cashpoints.TIME);
	        int ownerColumn = cashpointCursor.getColumnIndex(Cashpoints.OWNER_ID);
	        int latitudeColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_LATITUDE);
	        int longitudeColumn = cashpointCursor.getColumnIndex(Cashpoints.ADDRESS_LONGITUDE);
	        int countryColumn = cashpointCursor.getColumnIndex(Cashpoints.COUNTRY_ID);
	        
	        // Pole "CITY"
			cityStreet = cashpointCursor.getString(addressCityColumn);
			
	        // Pole "STREET"
			String street = cashpointCursor.getString(addressStreetColumn);
			cityStreet = cityStreet + " ul. " + street;

	        // Pole "MARKED"
			marked = (cashpointCursor.getShort(markedColumn) == 0) ? false : true;
			
			// Pole "INFO"
			info = cashpointCursor.getString(infoColumn);
			if (info == null || info.length() <= 0) {
				info = null;
			}
			
			// Pole "TIME"
			time = cashpointCursor.getString(timeColumn);
			if (time == null || time.length() <= 0 || "*".equals(time)) {
				time = null;
			}
			
			// Pole "OWNER"
			int ownerId = cashpointCursor.getInt(ownerColumn);
			Uri ownerUri = ContentUris.withAppendedId(Owners.CONTENT_URI, ownerId);
			
			// Tworze kursor dla Owner
	        Cursor ownerCursor = managedQuery(ownerUri, OWNERS_PROJECTION, null, null, Owners.DEFAULT_SORT_ORDER);			
			if (ownerCursor != null && ownerCursor.moveToFirst()) {
				int nameColumn = ownerCursor.getColumnIndex(Owners.NAME);
				owner = ownerCursor.getString(nameColumn);
			}
			
			// Zamykam kursor dla Owner
			if (ownerCursor != null) {
				ownerCursor.close();
			}
			
			// Pole "latitude"
			latitude = cashpointCursor.getDouble(latitudeColumn);

			// Pole "longitude"
			longitude = cashpointCursor.getDouble(longitudeColumn);
			
			// Pole "COUNTRY i REGION"
			int countryId = cashpointCursor.getInt(countryColumn);
			Uri countryUri = ContentUris.withAppendedId(Countries.CONTENT_URI, countryId);
			
			// Tworze kursor dla Country
	        Cursor countryCursor = managedQuery(countryUri, COUNTRIES_PROJECTION, null, null, Countries.DEFAULT_SORT_ORDER);			
			if (countryCursor != null && countryCursor.moveToFirst()) {
				int nameColumn = countryCursor.getColumnIndex(Countries.NAME);
				int regionIdColumn = countryCursor.getColumnIndex(Countries.REGION_ID);
				
				// Pobieram powiat
				regionCountry = countryCursor.getString(nameColumn);
				
				// Pobieram identyfikator regionu
				int regionId = countryCursor.getInt(regionIdColumn);
				
				// Tworze kursor dla Region
				Uri regionUri = ContentUris.withAppendedId(Regions.CONTENT_URI, regionId);
		        Cursor regionCursor = managedQuery(regionUri, REGIONS_PROJECTION, null, null, Regions.DEFAULT_SORT_ORDER);			
		        if (regionCursor != null && regionCursor.moveToFirst()) {
		        	int regionNameColumn = regionCursor.getColumnIndex(Regions.NAME);

					// Pobieram wojewodztwo
					String region = regionCursor.getString(regionNameColumn);
					if (region != null && region.length() > 0) {
						regionCountry = region + ", " + regionCountry;
					} else {
						//Log.w(LOG_TAG, "Wojewodztwo jest niepoprawne!");	
					}
		        } else {
		        	//Log.w(LOG_TAG, "Kursor wojewodztwa jest bledny!");
		        }
		        
		        // Zamykam kursor dla Region
				if (regionCursor != null) {
					regionCursor.close();
				}
			} else {
				regionCountry = null;
			}
			
			// Zamykam kursor dla Country
			if (countryCursor != null) {
				countryCursor.close();
			}
			
	    } else {
	    	//Log.w(LOG_TAG, "Brak bankomatu o id: " + selectedId);
	    	quit();
	    }
		
		// Zamykam kursor
		if (cashpointCursor != null) {
			cashpointCursor.close();
		}
	}

	/**
     * Funkcja zmienia pole "ulubione" w wybranym bankomacie.
     */
    private void changeMarkedState() {
    	if (uriOfSelectedCashpoint != null) {
    		// Pobieram pole "Ulubione"
            CheckBox markedCheckBox = (CheckBox)findViewById(R.id.cashpointMarkedCheckBox);
    		
			// Zakres zmian do wprowadzenia
			ContentValues values = new ContentValues();
	        values.put(Cashpoints.MARKED, markedCheckBox.isChecked());
	        
	        // Aktualizacja
	        CashpointActivity.this.getApplicationContext().getContentResolver().update(uriOfSelectedCashpoint, values, null, null);
    	}
	}

	/**
     * Pokazanie danych bankomatu na mapie.
     */
    private void showMap() {
      	Intent intent = new Intent(this, CashpointMapActivity.class);
      	
      	double[] latitudeArray = {latitude};
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_LATITUDE, latitudeArray);
    	
    	double[] longitudeArray = {longitude};
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_LONGITUDE, longitudeArray);
    	
    	String[] cityStreetArray = {cityStreet};
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_CITY_STREET, cityStreetArray);
    	
    	String[] ownerArray = {owner};
    	intent.putExtra(PreferencesManager.CASHPOINT_SELECTED_OWNER, ownerArray);
    	
    	startActivity(intent);
	}

    /**
     * Wyslanie danych bankomatu przez sms do wybranej osoby.
     */
    private void sms() {
    	// Budowanie tresci SMSa
    	StringBuilder sb = new StringBuilder();
    	
    	if (regionCountry != null) {
    		sb.append(regionCountry);
    		sb.append(", ");
    	}
    	
    	if (cityStreet != null) {
    		sb.append(cityStreet);
    		sb.append(", ");
    	}

    	if (info != null) {
    		sb.append(info);
    		sb.append(", ");
    	}

    	if (time != null && !time.equals("*")) {
    		sb.append(time);
    		sb.append(", ");
    	}
    	
    	if (owner != null) {
    		sb.append(owner);
    	}
    	
    	// Wyslanie SMSa
    	Intent smsIntent = new Intent(Intent.ACTION_VIEW);
    	smsIntent.putExtra("sms_body", sb.toString());
    	smsIntent.setType("vnd.android-dir/mms-sms");
    	startActivity(smsIntent);
	}

	/**
     * Funkcja budowania menu.
     */
    public boolean onCreateOptionsMenu(Menu menu) {
        menu.add(0, MENU_SHOW_MAP, 0, getString(R.string.cashpoint_show_map_button)).setIcon(R.drawable.menu_map);
        menu.add(1, MENU_SMS, 0, getString(R.string.cashpoint_sms_button)).setIcon(R.drawable.menu_send);
        menu.add(2, MENU_QUIT, 0, getString(R.string.menu_exit)).setIcon(R.drawable.menu_close);
        return true;
    }

    /**
     * Obsluga zdarzenia wybrania opcji z menu.
     */
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
        	case MENU_QUIT: {
        		quit();
        		return true;
        	}
        	case MENU_SHOW_MAP: {
        		showMap();
        		return true;
        	}
        	case MENU_SMS: {
        		sms();
        		return true;
        	}
        }
	    
        return false;
    }

    /**
     * Funkcja konczenia aplikacji.
     */
    private void quit() {
    	this.finish();
    }
}